package tk.heimashuma.store.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;


@Component
public class RedisUtil {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    public boolean expire(String key,long time) {
        try {
            if(time  > 0L){
                redisTemplate.expire(key,time, TimeUnit.SECONDS);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     * @param key 键
     * @param item 项
     * @param value 值
     * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public boolean hset(String  key,String item,Object value,long time){
        try {
            redisTemplate.opsForHash().put(key,item,value);
            if(time > 0L){
                expire(key,time);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * HashGet
     * @param key 键 不能为null
     * @param item 项 不能为null
     * @return
     */
    public Object  hget(String key,String item){
        return redisTemplate.opsForHash().get(key,item);
    }

    public long sSetAndTime(String key, long time, String... values) {
        try {
            long count = redisTemplate.opsForSet().add(key,values);
            if (time > 0)
                expire(key, time);
            return count;
        }catch (Exception e){
            e.printStackTrace();
            return -1L;
        }
    }

    /**
     * 通过key得到值
     * @param key
     * @return
     */
    public Set<String> sGet(String key){
        try {
            Set<String> members = redisTemplate.opsForSet().members(key);
            return members;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
